package com.kvest.gpsservicetracker.datastorage;

import com.kvest.gpsservicetracker.datamodel.DBLocationItem;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

import java.util.ArrayList;
import java.util.List;

public class GPSDatabase {
    private static final String DATABASE_NAME = "gps.db";
    private static final int DATABASE_VERSION = 1;

    private GPSDatabaseHelper helper;

    public GPSDatabase(Context context) {
        helper = new GPSDatabaseHelper(context);
    }

    public long add(DBLocationItem element) {
        //Get writeble BD
        SQLiteDatabase db = helper.getWritableDatabase();
        try
        {
            //Set values to add
            ContentValues values = new ContentValues();
            values.put(GPSTableMetadata.FIELD_TIME, element.getTime());
            values.put(GPSTableMetadata.FIELD_LATITUDE, element.getLatitude());
            values.put(GPSTableMetadata.FIELD_LONGITUDE, element.getLongitude());
            values.put(GPSTableMetadata.FIELD_BEARING, element.getBearing());
            values.put(GPSTableMetadata.FIELD_ALTITUDE, element.getAltitude());
            values.put(GPSTableMetadata.FIELD_SPEED, element.getSpeed());
            values.put(GPSTableMetadata.FIELD_ACCURACY, element.getAccuracy());

            //Add
            return db.insert(GPSTableMetadata.TABLE_NAME, null, values);
        }
        finally
        {
            //Close DB
            db.close();
        }
    }

    public List<DBLocationItem> getAll() {
        List<DBLocationItem> result = new ArrayList<DBLocationItem>();

        //Get DB
        SQLiteDatabase db = helper.getReadableDatabase();
        try
        {
            //Select all data
            Cursor items = db.rawQuery(GPSTableMetadata.GET_ALL_DATA, null);
            items.moveToFirst();
            while (!items.isAfterLast())
            {
                //Parse data of record
                DBLocationItem element = new DBLocationItem(items.getLong(1));
                element.setLatitude(items.getDouble(2));
                element.setLongitude(items.getDouble(3));
                element.setBearing(items.getFloat(4));
                element.setAltitude(items.getFloat(5));
                element.setSpeed(items.getFloat(6));
                element.setAccuracy(items.getFloat(7));

                //Add element to resultlist
                result.add(element);

                //Go to next record
                items.moveToNext();
            }
            items.close();
        }
        finally
        {
            //Close DB
            db.close();
        }

        return result;
    }

    public boolean delete(long time) {
        //Get writeble BD
        SQLiteDatabase db = helper.getWritableDatabase();
        try
        {
            //delete
            return db.delete(GPSTableMetadata.TABLE_NAME, GPSTableMetadata.FIELD_TIME + "=?", new String[]{Long.toString(time)}) > 0;
        }
        finally
        {
            //Close DB
            db.close();
        }
    }

    private static class GPSTableMetadata implements BaseColumns {
        public static final String TABLE_NAME = "gps_table";
        public static final String FIELD_TIME = "time";
        public static final String FIELD_LATITUDE = "latitude";
        public static final String FIELD_LONGITUDE = "longitude";
        public static final String FIELD_BEARING = "bearing";
        public static final String FIELD_ALTITUDE = "altitude";
        public static final String FIELD_SPEED = "speed";
        public static final String FIELD_ACCURACY = "accuracy";

        public static final String CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + "(" + _ID + " integer primary key autoincrement," +
                                                                                           FIELD_TIME + " integer," +
                                                                                           FIELD_LATITUDE + " REAL DEFAULT 0," +
                                                                                           FIELD_LONGITUDE + " REAL DEFAULT 0," +
                                                                                           FIELD_BEARING + " REAL DEFAULT 0," +
                                                                                           FIELD_ALTITUDE + " REAL DEFAULT 0," +
                                                                                           FIELD_SPEED + " REAL DEFAULT 0," +
                                                                                           FIELD_ACCURACY + " REAL DEFAULT 0);";
        public static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";

        private static final String GET_ALL_DATA = "SELECT " + _ID + ", " + FIELD_TIME + ", " + FIELD_LATITUDE + ", " +
                                                    FIELD_LONGITUDE + ", " + FIELD_BEARING + ", " + FIELD_ALTITUDE + ", " + FIELD_SPEED +
                                                    ", " + FIELD_ACCURACY + " FROM " + TABLE_NAME + ";";
    }

    //Helper for database
    private static class GPSDatabaseHelper extends SQLiteOpenHelper
    {
        public GPSDatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(GPSTableMetadata.CREATE_TABLE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            //Nothing to do
        }
    }
}
